//
//  KKZAppDelegate.m
//  KKZ
//
//  Created by Bismarrck on 11-7-20.
//  Copyright 2011年 Tsinghua University. All rights reserved.
//

#import "KKZAppDelegate.h"
#import "CustomTabBarViewController.h"
#import "UserDefault.h"

@implementation KKZAppDelegate


@synthesize window=_window;
@synthesize viewController=_viewController;
@synthesize manager = _manager;
@synthesize myCurrentLocation = _myCurrentLocation;
@synthesize geocoder = _geocoder;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Alloc the location manager
    _manager = [[CLLocationManager alloc] init];
    _manager.delegate = self;
    _manager.desiredAccuracy = kCLLocationAccuracyBest;
    if (![CLLocationManager locationServicesEnabled]) {
        [CLLocationManager locationServicesEnabled];
    }
    [_manager startUpdatingLocation];
    
    // Load the view controllers
    self.viewController = [CustomTabBarViewController sharedTabBarController];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

- (void)dealloc
{
    [_window release];
    [_viewController release];
    [_myCurrentLocation release];
    [_geocoder release];
    [_manager release];
    [super dealloc];
}

#pragma mark -
#pragma mark - Location Manager Delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // Get my location infomation
    if (_myCurrentLocation == nil) {
        _myCurrentLocation = [[CLLocation alloc] init];
        _myCurrentLocation = newLocation;
    }
    
    [_manager stopUpdatingLocation];
    
    // Parse the GPS coordinates using MKReverseCoder
    _geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:self.myCurrentLocation.coordinate];
    _geocoder.delegate = self;
    [self.geocoder start];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *errorType = (error.code == kCLErrorDenied) ? @"Access Denied" : @"Unknown Error";
    UIAlertView *alert = [[UIAlertView alloc]
						  initWithTitle:@"Error getting Location"
						  message:errorType
						  delegate:nil
						  cancelButtonTitle:@"Okay"
						  otherButtonTitles:nil];
    [alert show];
    [alert release];
}

#pragma mark -
#pragma makr - MKGeocoder Delegate 

- (void)setMyLocalCity:(NSString *)cityName district:(NSString *)district
{
    USER_DEFAULT_CITY_WRITE(cityName);
    USER_DEFAULT_DISTRICT_WRITE(district);
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    if (self.geocoder) {
        MKPlacemark *myPlaceMark = placemark;
        
        NSString *city = myPlaceMark.locality;
        NSString *district = myPlaceMark.subLocality;
        
        [self setMyLocalCity:city district:district];
    }
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
    
}

@end
